// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// T [author] rhyme_lph
// H [email]  rhymelph@gmail.com
// j [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/a.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/provider/dashboard/contact/main_business_contact_provider.dart';
import 'package:finance_app/src/router_gen/router_meta.dart';
import 'package:finance_app/src/utils/language_utils.dart';
import 'package:finance_app/src/widgets/button/add_button.dart';
import 'package:finance_app/src/widgets/button/assistant_button.dart';
import 'package:finance_app/src/widgets/button/filter_button.dart';
import 'package:finance_app/src/widgets/button/normal_down_button.dart';
import 'package:finance_app/src/widgets/button/normal_float_svg_button.dart';
import 'package:finance_app/src/widgets/button/normal_popup_button.dart';
import 'package:finance_app/src/widgets/chip/normal_chip.dart';
import 'package:finance_app/src/widgets/common_app_bar.dart';
import 'package:finance_app/src/widgets/dash_board/contacts_tag_item.dart';
import 'package:finance_app/src/widgets/input/search_input_field.dart';
import 'package:finance_app/src/widgets/list_item/list_header_item.dart';
import 'package:finance_app/src/widgets/wrapper/normal_form_wrapper.dart';
import 'package:flutter/material.dart';
import 'package:flutter_sticky_header/flutter_sticky_header.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'business_contacts_page.dart';

@RouterMeta(paramName: "mainBusinessContactPage")
class MainBusinessContactPage extends StatefulWidget {
  final String initFilter;

  const MainBusinessContactPage({Key key, this.initFilter}) : super(key: key);

  @override
  _MainBusinessContactPageState createState() =>
      _MainBusinessContactPageState();
}

class _MainBusinessContactPageState extends State<MainBusinessContactPage>
    with PagePresenter<MainBusinessContactPage, MainBusinessContactProvider> {
  @override
  void initState() {
    super.initState();
    if (widget.initFilter != null) {
      provider.currentSelectFilterList = widget.initFilter.split(',');
    }
  }

  @override
  PreferredSizeWidget get appBar =>
      getDefaultAppBar(title: S.current.business_contacts, actions: [
        AssistantButton(
          paddingRight: 0.0,
          entryPoint: S.current.business_contacts,
        ),
        listBuilder<List<String>>(
          selector: (_, __) => List.from(__.menuList),
          builder: (BuildContext context, value, Widget child) =>
              NormalMorePopupButton(
            horizontalPadding: getDp(10),
            menuList: provider.menuList,
            onSelect: provider.onSelectMenu,
          ),
        )
      ]);

  @override
  Widget get buildEmptyWidget => ColoredBox(
        color: Colors.white,
        child: Stack(
          children: [
            Column(
              children: [
                AppSpaces.h20,
                SearchInputField(
                  controller: provider.searchController,
                  focusNode: provider.searchFocusNode,
                ),
                AppSpaces.h20,
                listBuilder<String>(
                  selector: (_, __) => __.searchController.text,
                  builder: (BuildContext context, String value, Widget child) =>
                      provider.groupMap.isEmpty && value.length > 0
                          ? NormalFormWrapper(
                              child: AddButton(
                                title: '${S.current.add} “$value”',
                                onTap: provider.onAddBusiness,
                              ),
                            )
                          : Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                _buildSortContactSelect(),
                                FilterButton(
                                  onPressed: provider.onShowFilter,
                                ),
                              ],
                            ),
                ),
                AppSpaces.h20,
                _buildFilterList(),
                Expanded(
                  child: super.buildEmptyWidget,
                ),
              ],
            ),
            _buildBottomButton(true),
          ],
        ),
      );

  @override
  Widget get buildWidget => ColoredBox(
      color: Colors.white,
      child: listBuilder<bool>(
        selector: (_, __) => __.buttonBarIsUp,
        builder: (BuildContext context, bool value, Widget child) => Stack(
          children: [
            child,
            _buildBottomButton(value),
            // _buildTop(),
          ],
        ),
        child: _buildRecordList(),
      ));

  Widget _buildRecordList() => Column(
        children: [
          AppSpaces.h20,
          SearchInputField(
            controller: provider.searchController,
            focusNode: provider.searchFocusNode,
          ),
          AppSpaces.h20,
          listBuilder<String>(
            selector: (_, __) => __.searchController.text,
            builder: (BuildContext context, String value, Widget child) =>
                provider.groupMap.isEmpty && value.length > 0
                    ? NormalFormWrapper(
                        child: AddButton(
                          title: '${S.current.add} “$value”',
                          onTap: provider.onAddBusiness,
                        ),
                      )
                    : Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          _buildSortContactSelect(),
                          FilterButton(
                            onPressed: provider.onShowFilter,
                          ),
                        ],
                      ),
          ),
          AppSpaces.h20,
          _buildFilterList(),
          Expanded(
            child: listBuilder<Map<String, List<BusinessContactEntity>>>(
              selector: (_, __) => Map.from(__.groupMap),
              builder: (BuildContext context,
                      Map<String, List<BusinessContactEntity>> value,
                      Widget child) =>
                  value.isEmpty
                      ? super.buildEmptyWidget
                      : SmartRefresher(
                          controller: provider.refreshController,
                          onRefresh: provider.onRefresh,
                          onLoading: provider.onLoadMore,
                          enablePullUp: false,
                          child: CustomScrollView(
                            controller: provider.controller,
                            slivers: buildSearchWidget(),
                          ),
                        ),
            ),
          ),
        ],
      );

  Widget _buildBottomButton(bool isTop) => AnimatedPositioned(
      duration: Duration(milliseconds: 300),
      left: 0.0,
      right: 0.0,
      bottom: isTop
          ? MediaQuery.of(context).padding.bottom + getDp(40)
          : -getDp(60),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          NormalFloatSvgButton(
            onTap: provider.onNavAdd,
            asset: A.assetsImagesDashboardAdd,
          ),
        ],
      ));

  Widget _buildFilterList() {
    return listBuilder<int>(
        builder: (BuildContext context, int value, Widget child) => value == 0
            ? Container()
            : Container(
                height: getDp(30),
                clipBehavior: Clip.none,
                margin: EdgeInsets.only(bottom: getDp(15)),
                alignment: Alignment.centerLeft,
                child: ListView.separated(
                  padding: EdgeInsets.symmetric(
                    horizontal: getDp(10),
                  ),
                  scrollDirection: Axis.horizontal,
                  shrinkWrap: true,
                  itemBuilder: (BuildContext context, int index) =>
                      _buildFilterItem(context, index),
                  itemCount: value,
                  separatorBuilder: (BuildContext context, int index) {
                    return Container(
                      width: getDp(15),
                    );
                  },
                ),
              ),
        selector: (_, __) => __.filterListLength);
  }

  Widget _buildSortContactSelect() {
    return listBuilder<String>(
        builder: (BuildContext context, String value, Widget child) =>
            NormalDownButton(
              title: value,
              onTap: provider.onSelectSortContact,
            ),
        selector: (_, __) => __.currentSelectSortContact ?? '');
  }

  Widget _buildFilterItem(BuildContext context, int index) {
    return listBuilder<String>(
        builder: (BuildContext context, String value, Widget child) =>
            NormalChip(
              title: LanguageUtils.translateFilter(value),
              onClose: () => provider.onRemoveFilter(value),
            ),
        selector: (_, __) => __.currentSelectFilterList[index]);
  }

  List<Widget> buildSearchWidget() {
    return provider.groupMap.entries
        .toList()
        .map((e) => buildSliver(e.key, e.value))
        .toList();
  }

  Widget buildSliver(String title, List<BusinessContactEntity> data) =>
      SliverStickyHeader(
        header: buildSliverHeader(title: title),
        sliver: SliverList(
          delegate: SliverChildBuilderDelegate(
            (context, i) => buildSliverItem(data, i),
            childCount: data.length,
          ),
        ),
      );

  Widget buildSliverItem(List<BusinessContactEntity> data, int i) {
    return listBuilder<BusinessContactEntity>(
        selector: (_, __) => data[i],
        builder:
            (BuildContext context, BusinessContactEntity value, Widget child) =>
                ContactsTagItem(
                  onTap: () => provider.onSelectBusinessContact(data[i]),
                  title: data[i].name,
                  isSelect: false,
                  isSelectMode: false,
                  isLastItem: data.length == i + 1,
                  isCheckStar: value.isFavorite == 1,
                  hasCreditBalance:
                      (value.totalUnpaidCredit + value.totalUnpaidDebit) > 0,
                  onClickStar: () => provider.onClickStar(value),
                  isOverdue: value.isOverdue == 1,
                  tags: [
                    if (value.isSupplier == 1) 'S',
                    if (value.isClient == 1) 'C'
                  ],
                ));
  }

  Widget buildSliverHeader({String title}) {
    final String _title = title.isEmpty ? "*" : title;
    if (_title == '*' &&
        provider.currentSelectSortContact == S.current.transaction_amount)
      return Container();

    return ListHeaderItem(
      title: _title,
    );
  }
}
